package com.feemanage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cfg.domain.ClaimProjectShow;
import com.cfg.mapper.ClaimProjectShowMapper;
import com.common.core.page.PageDomain;
import com.feemanage.domain.ProjectType;
import com.feemanage.domain.SysSnrule;
import com.feemanage.mapper.ProjectTypeExecuteMapper;
import com.feemanage.mapper.SysSnruleMapper;
import com.feemanage.service.ISysSnruleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SysSnruleServiceImpl implements ISysSnruleService {

    @Autowired
    private SysSnruleMapper baseMapper;

    @Autowired
    private ClaimProjectShowMapper projectShowMapper;

    @Autowired
    private ProjectTypeExecuteMapper typeExecuteMapper;

    /**
     * 查询编号规则列表
     * @param pageDomain
     * @param sysSnrule
     * @return
     */
    @Override
    public IPage<SysSnrule> selectList(PageDomain pageDomain, SysSnrule sysSnrule) {
        Page<SysSnrule> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        QueryWrapper<SysSnrule> wrapper = Wrappers.query();
        wrapper.orderByAsc("id");
        IPage<SysSnrule> list= baseMapper.selectSnruleList(page,wrapper);
        List<ProjectType> typeList = typeExecuteMapper.selectProjectTypeList(new QueryWrapper<>());
        for (SysSnrule u : list.getRecords()) {
            if(StringUtils.isNotEmpty(u.getApplyrange())){
                u.setApplyrangeName(String.join(",",getFilteredNames(u.getApplyrange(), typeList)));
            }
        }
        return list;
    }

    public List<String> getFilteredNames(String applyRange, List<ProjectType> typeList) {
        // 分割applyRange并过滤空字符串
        Set<String> appliedCodes = Arrays.stream(applyRange.split(","))
                .filter(code -> !code.isEmpty())
                .collect(Collectors.toSet());

        // 创建code到ProjectType的映射以便快速查找
        Map<String, ProjectType> codeToType = new HashMap<>();
        for (ProjectType type : typeList) {
            codeToType.put(type.getCode(), type);
        }

        List<String> result = new ArrayList<>();
        for (String code : appliedCodes) {
            ProjectType type = codeToType.get(code);
            if (type == null) continue; // 如果code不存在于typeList中，跳过

            String upCode = type.getUpCode();
            // 如果当前code没有父节点，或父节点不在appliedCodes中，则保留
            if (StringUtils.isEmpty(upCode) || !appliedCodes.contains(upCode)) {
                result.add(type.getName());
            }
        }
        return result;
    }

    /**
     * 编辑规则
     * @param snrule
     * @return
     */
    @Override
    public Boolean editSnrule(SysSnrule snrule) {
        return baseMapper.updateById(snrule) >0;
    }



    @Override
    public String generateCode(String type, String projectId){
        if(type!=null && StringUtils.isNotBlank(type) && projectId !=null && StringUtils.isNotBlank(projectId)){
            String projectClass = null;
            if(type.equalsIgnoreCase("3")){
                projectClass = "xJProject";
            }else {
                ClaimProjectShow show = projectShowMapper.selectClaimProjectClass(new QueryWrapper<ClaimProjectShow>().eq("vp.id", projectId).last(" limit 1"));
                projectClass = ObjectUtil.isNotNull(show)?show.getProjectClass():null;
            }
            if (StringUtils.isNotEmpty(projectClass)){
                SysSnrule snrule = baseMapper.selectOne(new QueryWrapper<SysSnrule>().eq("project_class",projectClass)
                        .eq("type",type).last(" LIMIT 1"));

                if (ObjectUtil.isNotNull(snrule) && StringUtils.isNotEmpty(snrule.getExpressionHtml())){
                    String[] rule = snrule.getExpressionHtml().split("\\+");
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(rule[1].replaceAll("^\\{|\\}$", ""));
                    String prefix =rule[0]+ LocalDateTime.now().format(formatter);
                    Long number = Long.valueOf(rule[rule.length-1]);
                    snrule.setPrefix(prefix);
                    snrule.setNumber(number);
                    Long sequence = baseMapper.selecMaxPrefix(snrule);
                    String code = prefix+ String.format("%0"+number+"d",  Math.addExact(sequence, 1));
                    return  code;
                }
            }
        }
        return null;
    }
}
